package com.jack.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LB implements LoadBalancer {


    private AtomicInteger requestCount = new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;
        do{
            current = this.requestCount.get();
            next = current + 1;
        } while (!this.requestCount.compareAndSet(current, next));
        System.out.println("请求次数："+next);
        return next;
    }


    @Override
    public ServiceInstance instances(List<ServiceInstance> instances) {
        int i = getAndIncrement() % instances.size();
        return instances.get(i);
    }
}
